<?php
	/**
	 * MusicNet Alignment Tool: Alignment Helper Functions
	 *
	 * Copyright (c) 2010 Joe Lambert
	 * 
	 * Permission is hereby granted, free of charge, to any person obtaining
	 * a copy of this software and associated documentation files (the
	 * "Software"), to deal in the Software without restriction, including
	 * without limitation the rights to use, copy, modify, merge, publish,
	 * distribute, sublicense, and/or sell copies of the Software, and to
	 * permit persons to whom the Software is furnished to do so, subject to
	 * the following conditions:
	 * 
	 * The above copyright notice and this permission notice shall be
	 * included in all copies or substantial portions of the Software.
	 * 
	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
	 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
	 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
	 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
	 *  
	 * @author Joe Lambert
	 * @version 1.0
	 * @copyright Joe Lambert, 23 August, 2010
	 **/
	
	// Include required files
	require_once(dirname(__FILE__).'/../shared/database.php');
	require_once(dirname(__FILE__)."/../shared/musicnet.php");
	
	class alignment
	{
		public static function find_matches()
		{
			Database::instance();
			
			$query = "SELECT id, label, hash, COUNT( hash ) AS count FROM `items` GROUP BY hash	ORDER BY count DESC";
			
			$result = mysql_query($query);
			
			$i = 0;
			
			while($row = mysql_fetch_assoc($result))
			{
				if($row['count'] > 1)
				{
					$i++;
					
					$query = sprintf("SELECT * FROM `items` WHERE hash = '%s'", mysql_real_escape_string($row['hash']));
					$matches = mysql_query($query);
					
					$ids = array();
					$found_id = null;
					$label = "";
					
					while($r = mysql_fetch_assoc($matches))
					{
						$ids[] = $r['id'];
						$label = $r['label'];
						
						if($r['match_id'])
							$found_id = $r['match_id'];
					}
					
					$md5 = MusicNet::createGroupID($ids);
					
					// Has one of the items we think matches already been associated to a group?
					if($found_id)
						$md5 = $found_id;
					
					// Add the group
					$match_query = sprintf("INSERT INTO `matches` (id, canonical_label) VALUES ('%s', '%s')",
										mysql_real_escape_string($md5),
										mysql_real_escape_string($label));
										
					$insert = mysql_query($match_query);
					
					if(!$insert)
					{
						$error = mysql_error();
						// Check to see if the group has already been added?
						$result = mysql_query("SELECT * FROM `matches` WHERE id = '".mysql_real_escape_string($md5)."'");
						
						if(mysql_num_rows($result) == 0)
							die("$error\n");
					}
						
					
					// Update all relevant items to point to that group
					$update_query = sprintf("UPDATE `items` SET match_id = '%s' WHERE id IN ('%s')", 
										mysql_real_escape_string($md5),
										implode("', '", $ids));
					
					$update = mysql_query($update_query);
					
					if(!$update)
						die(mysql_error()."\n");
				}
				else
					break;
			}
			
			echo "$i matches found\n";
		}
	}
	
	alignment::find_matches();
?>